package com.yanqu.road.dataHelper.del;

import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.dataHelper.crossServer.CrossServer;
import com.yanqu.road.dataHelper.del.mgr.CrossBattleDelMgr;
import com.yanqu.road.dataHelper.del.mgr.CrossDelMgr;
import com.yanqu.road.dataHelper.del.mgr.GameDelMgr;
import com.yanqu.road.dataHelper.gameServer.GameServer;
import com.yanqu.road.dataHelper.manager.ServerMgr;
import com.yanqu.road.entity.servercenter.ServerInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DelAction {

    private Map<Long,GameServer> gameServerMap = new ConcurrentHashMap<>();

    private Map<Long, CrossServer> crossServerMap = new ConcurrentHashMap<>();

    protected static Logger logger = LogManager.getLogger(TempDao.class.getName());

    public void go(List<Long> serverList){
        logger.error("开始一波删除");
        if(GameDelMgr.getTableMap().size() != 0 || GameDelMgr.getTableLogMap().size() != 0){
            logger.error("开始删除server的user和log库");
            for(long serverId : serverList){
                for(String tableName : GameDelMgr.getTableMap().keySet()){
                    boolean hasData = select(getGameServer(serverId),GameDelMgr.getTableMap().get(tableName));
                    if(hasData){
                        logger.error("serverId:{},{}表有数据开始删除",serverId,tableName);
                        long startTime = System.currentTimeMillis();
                        int count = delete(getGameServer(serverId),GameDelMgr.getTableMap().get(tableName));
                        long endTime = System.currentTimeMillis();
                        logger.error("serverId:{},{}表删除{}数据,用时{}毫秒",serverId,tableName,count,endTime - startTime);
                    }
                }
                for(String tableName : GameDelMgr.getTableLogMap().keySet()){
                    boolean hasData = selectLog(getGameServer(serverId),GameDelMgr.getTableLogMap().get(tableName));
                    if(hasData){
                        logger.error("serverId:{},{}表有数据删除",serverId,tableName);
                        long startTime = System.currentTimeMillis();
                        int count = deleteLog(getGameServer(serverId),GameDelMgr.getTableLogMap().get(tableName));
                        long endTime = System.currentTimeMillis();
                        logger.error("serverId:{},{}表删除{}数据,用时{}毫秒",serverId,tableName,count,endTime - startTime);
                    }
                }
            }
        }
        if(CrossDelMgr.getCrossIdList().size() != 0){
            logger.error("开始删除cross的union库");
            for(long crossServerId : CrossDelMgr.getCrossIdList()){
                for(String tableName : CrossDelMgr.getTableMap().keySet()){
                    boolean hasData = selectCross(getCrossServer(crossServerId),CrossDelMgr.getTableMap().get(tableName));
                    if(hasData){
                        logger.error("crossId:{},{}表有数据删除",crossServerId,tableName);
                        long startTime = System.currentTimeMillis();
                        int count = deleteCross(getCrossServer(crossServerId),CrossDelMgr.getTableMap().get(tableName));
                        long endTime = System.currentTimeMillis();
                        logger.error("crossId:{},{}表删除{}数据,用时{}毫秒",crossServerId,tableName,count,endTime - startTime);
                    }
                }
            }
        }
        if(CrossBattleDelMgr.getCrossIdList().size() != 0){
            logger.error("开始删除cross的battle库");
            for(long crossServerId : CrossBattleDelMgr.getCrossIdList()){
                for(String tableName : CrossBattleDelMgr.getTableMap().keySet()){
                    boolean hasData = selectCross(getCrossServer(crossServerId),CrossBattleDelMgr.getTableMap().get(tableName));
                    if(hasData){
                        logger.error("crossId:{},{}表有数据删除",crossServerId,tableName);
                        long startTime = System.currentTimeMillis();
                        int count = deleteCross(getCrossServer(crossServerId),CrossBattleDelMgr.getTableMap().get(tableName));
                        long endTime = System.currentTimeMillis();
                        logger.error("crossId:{},{}表删除{}条数据,用时{}毫秒",crossServerId,tableName,count,endTime - startTime);
                    }
                }
            }
        }
    }

    private GameServer getGameServer(long serverId){
        if(!gameServerMap.containsKey(serverId)){
            ServerInfo serverInfo = ServerMgr.getServerInfoList().get(serverId);
            GameServer gServer = new GameServer(serverInfo);
            gameServerMap.put(serverId,gServer);
        }
        return gameServerMap.get(serverId);
    }

    private CrossServer getCrossServer(long serverId){
        if(!crossServerMap.containsKey(serverId)){
            CrossServer cServer = new CrossServer(serverId);
            crossServerMap.put(serverId,cServer);
        }
        return crossServerMap.get(serverId);
    }

    private boolean select(GameServer gameServer,List<String> infoList){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT 1 as bang FROM "+infoList.get(0)+"" +
                " WHERE "+infoList.get(2) +" < '"+ infoList.get(3) +"' LIMIT 1";
        try {
            call = gameServer.getConnection().prepareCall(sql);
            rs = call.executeQuery();
            if(rs.next()){
                return true;
            }
        } catch (SQLException ex) {
            gameServer.getLogger().error("异常错误", ex);
        } finally {
            gameServer.closeConnection(call, rs);
        }
        return false;
    }

    private int delete(GameServer gameServer,List<String> infoList){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "DELETE FROM "+infoList.get(0)+"" +
                " WHERE "+infoList.get(2) +" < '"+ infoList.get(3) +"' LIMIT " + infoList.get(1);
        try {
            call = gameServer.getConnection().prepareCall(sql);
            return call.executeUpdate(sql);
        } catch (SQLException ex) {
            gameServer.getLogger().error("异常错误", ex);
        } finally {
            gameServer.closeConnection(call, rs);
        }
        return 0;
    }

    private boolean selectLog(GameServer gameServer,List<String> infoList){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT 1 as bang FROM "+infoList.get(0)+"" +
                " WHERE "+infoList.get(2) +" < '"+ infoList.get(3) +"' LIMIT 1";
        try {
            call = gameServer.getLogConnection().prepareCall(sql);
            rs = call.executeQuery();
            if(rs.next()){
                return true;
            }
        } catch (SQLException ex) {
            gameServer.getLogger().error("异常错误", ex);
        } finally {
            gameServer.closeConnection(call, rs);
        }
        return false;
    }

    private int deleteLog(GameServer gameServer,List<String> infoList){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "DELETE FROM "+infoList.get(0)+"" +
                " WHERE "+infoList.get(2) +" < '"+ infoList.get(3) +"' LIMIT " + infoList.get(1);
        try {
            call = gameServer.getLogConnection().prepareCall(sql);
            return call.executeUpdate(sql);
        } catch (SQLException ex) {
            gameServer.getLogger().error("异常错误", ex);
        } finally {
            gameServer.closeConnection(call, rs);
        }
        return 0;
    }

    private boolean selectCross(CrossServer crossServer,List<String> infoList){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT 1 as bang FROM "+infoList.get(0)+"" +
                " WHERE "+infoList.get(2) +" < '"+ infoList.get(3) +"' LIMIT 1";
        try {
            call = crossServer.getConnection().prepareCall(sql);
            rs = call.executeQuery();
            if(rs.next()){
                return true;
            }
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return false;
    }

    private int deleteCross(CrossServer crossServer,List<String> infoList){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "DELETE FROM "+infoList.get(0)+"" +
                " WHERE "+infoList.get(2) +" < '"+ infoList.get(3) +"' LIMIT " + infoList.get(1);
        try {
            call = crossServer.getConnection().prepareCall(sql);
            return call.executeUpdate(sql);
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return 0;
    }
}
